// 图表组件封装

/**
 * 图表管理器
 */
class ChartManager {
    constructor() {
        this.charts = new Map();
        this.resizeObserver = null;
        this.initResizeObserver();
    }

    /**
     * 初始化窗口尺寸监听
     */
    initResizeObserver() {
        if (window.ResizeObserver) {
            this.resizeObserver = new ResizeObserver(
                throttle(() => {
                    this.charts.forEach(chart => {
                        if (chart && !chart.isDisposed()) {
                            chart.resize();
                        }
                    });
                }, 200)
            );
        }

        // 窗口resize事件备选方案
        window.addEventListener('resize', 
            throttle(() => {
                this.charts.forEach(chart => {
                    if (chart && !chart.isDisposed()) {
                        chart.resize();
                    }
                });
            }, 200)
        );
    }

    /**
     * 创建或获取图表实例
     */
    getChart(elementId) {
        if (this.charts.has(elementId)) {
            return this.charts.get(elementId);
        }

        const element = document.getElementById(elementId);
        if (!element) {
            console.error(`图表容器 ${elementId} 不存在`);
            return null;
        }

        const chart = echarts.init(element, 'dark');
        this.charts.set(elementId, chart);
        
        // 添加到resize观察器
        if (this.resizeObserver) {
            this.resizeObserver.observe(element);
        }

        return chart;
    }

    /**
     * 销毁图表实例
     */
    disposeChart(elementId) {
        if (this.charts.has(elementId)) {
            const chart = this.charts.get(elementId);
            if (chart && !chart.isDisposed()) {
                chart.dispose();
            }
            this.charts.delete(elementId);
        }
    }

    /**
     * 销毁所有图表实例
     */
    disposeAll() {
        this.charts.forEach((chart, elementId) => {
            this.disposeChart(elementId);
        });
    }
}

// 全局图表管理器实例
const chartManager = new ChartManager();

/**
 * 省份交易量环比图表（按日期横坐标的柱状图）
 */
function createProvinceCompareChart(elementId, data) {
    const chart = chartManager.getChart(elementId);
    if (!chart) return;

    const dateData = data.dateData || [];
    const provinces = data.provinces || [];
    const xAxisData = dateData.map(d => d.date);
    
    // 为每个省份创建一个数据系列
    const series = provinces.map((province, index) => {
        const provName = province.name || province.provName || province.code || province.provCode;
        const provCode = province.code || province.provCode;
        const color = getRandomColor(index);
        
        // 获取该省份在各个日期的交易量数据
        const provData = dateData.map(dateItem => {
            if (!dateItem.provinceData) return 0;
            const provDataForDate = dateItem.provinceData.find(p => 
                p.provCode === provCode || 
                p.provName === provName ||
                p.code === provCode ||
                p.name === provName
            );
            return provDataForDate ? provDataForDate.value : 0;
        });
        
        return {
            name: provName,
            type: 'bar',
            data: provData,
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: color },
                    { offset: 1, color: adjustColor(color, -30) }
                ])
            },
            emphasis: {
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: adjustColor(color, 20) },
                        { offset: 1, color: color }
                    ])
                }
            }
        };
    });

    const option = {
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            },
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            borderColor: '#4FC3F7',
            textStyle: {
                color: '#ffffff'
            },
            formatter: function(params) {
                let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].name}</div>`;
                params.forEach(param => {
                    result += `
                        <div style="margin: 3px 0;">
                            ${param.marker} ${param.seriesName}: ${formatNumber(param.value)}
                        </div>
                    `;
                });
                return result;
            }
        },
        legend: {
            data: series.map(s => s.name),
            top: '5%',
            textStyle: {
                color: '#ffffff'
            },
            type: 'scroll',
            pageIconColor: '#4FC3F7',
            pageIconInactiveColor: '#666',
            pageTextStyle: { color: '#ffffff' }
        },
        grid: {
            left: '3%',
            right: '3%',
            bottom: '10%',
            top: '20%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
            axisLine: {
                lineStyle: { color: '#4FC3F7' }
            },
            axisLabel: {
                color: '#ffffff',
                interval: 0,
                rotate: 45
            }
        },
        yAxis: {
            type: 'value',
            axisLine: {
                lineStyle: { color: '#4FC3F7' }
            },
            axisLabel: {
                color: '#ffffff',
                formatter: function(value) {
                    return formatNumber(value);
                }
            },
            splitLine: {
                lineStyle: {
                    color: 'rgba(79, 195, 247, 0.2)'
                }
            }
        },
        series: series,
        animationDuration: 1000,
        animationEasing: 'cubicOut'
    };

    chart.setOption(option, true);
}

/**
 * 交易量综合监控图表（包含交易量、成功笔数、失败笔数）
 */
function createTransactionComprehensiveChart(elementId, transactionData) {
    const chart = chartManager.getChart(elementId);
    if (!chart) return;

    const totalData = transactionData.totalData || [];
    const successData = transactionData.successData || [];
    const failData = transactionData.failData || [];
    const xAxisData = totalData.map(item => item.time);
    const totalValues = totalData.map(item => item.value);
    const successValues = successData.map(item => item.value);
    const failValues = failData.map(item => item.value);

    const option = {
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            },
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            borderColor: '#4FC3F7',
            textStyle: { color: '#ffffff' },
            formatter: function(params) {
                let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].name}</div>`;
                params.forEach(param => {
                    result += `
                        <div style="margin: 3px 0;">
                            ${param.marker} ${param.seriesName}: ${formatNumber(param.value)}
                        </div>
                    `;
                });
                return result;
            }
        },
        legend: {
            data: ['总交易量', '成功笔数', '失败笔数'],
            top: '5%',
            textStyle: { color: '#ffffff' }
        },
        grid: {
            left: '3%',
            right: '3%',
            bottom: '15%',
            top: '20%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
            axisLine: { lineStyle: { color: '#4FC3F7' } },
            axisLabel: { 
                color: '#ffffff',
                interval: Math.max(1, Math.floor(xAxisData.length / 8))
            }
        },
        yAxis: {
            type: 'value',
            name: '交易笔数',
            axisLine: { lineStyle: { color: '#4FC3F7' } },
            axisLabel: { 
                color: '#ffffff',
                formatter: formatNumber
            },
            splitLine: {
                lineStyle: { color: 'rgba(79, 195, 247, 0.2)' }
            }
        },
        series: [
            {
                name: '总交易量',
                type: 'line',
                data: totalValues,
                smooth: true,
                lineStyle: { color: '#4FC3F7', width: 3 },
                itemStyle: { color: '#4FC3F7' },
                symbol: 'circle',
                symbolSize: 4
            },
            {
                name: '成功笔数',
                type: 'line',
                data: successValues,
                smooth: true,
                lineStyle: { color: '#81C784', width: 2 },
                itemStyle: { color: '#81C784' },
                symbol: 'circle',
                symbolSize: 4
            },
            {
                name: '失败笔数',
                type: 'line',
                data: failValues,
                smooth: true,
                lineStyle: { color: '#F44336', width: 2 },
                itemStyle: { color: '#F44336' },
                symbol: 'triangle',
                symbolSize: 4
            }
        ],
        animationDuration: 1000,
        animationEasing: 'cubicOut'
    };

    chart.setOption(option, true);
}

/**
 * 中心成功率监控图表
 */
function createSuccessRateChart(elementId, data) {
    const chart = chartManager.getChart(elementId);
    if (!chart) return;

    const successRates = data.successRates || [];
    const xAxisData = [];
    const series = [];

    // 构建时间轴数据
    if (successRates.length > 0) {
        const firstCenter = successRates[0];
        if (firstCenter.data && firstCenter.data.length > 0) {
            xAxisData.push(...firstCenter.data.map(item => item.time));
        }
    }

    // 构建每个中心的成功率数据
    successRates.forEach((center, index) => {
        const centerData = center.data || [];
        const color = getRandomColor(index);
        
        series.push({
            name: center.centerName || center.center,
            type: 'line',
            data: centerData.map(item => item.value),
            smooth: true,
            lineStyle: {
                color: color,
                width: 3
            },
            itemStyle: { color: color },
            symbol: 'circle',
            symbolSize: 6,
            animationDuration: 1000
        });
    });

    const option = {
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            borderColor: '#4FC3F7',
            textStyle: { color: '#ffffff' },
            formatter: function(params) {
                let result = `<div style="font-weight: bold;">${params[0].name}</div>`;
                params.forEach(param => {
                    result += `
                        <div>${param.marker} ${param.seriesName}: ${formatPercent(param.value)}</div>
                    `;
                });
                return result;
            }
        },
        legend: {
            data: series.map(s => s.name),
            top: '5%',
            textStyle: { color: '#ffffff' }
        },
        grid: {
            left: '3%',
            right: '3%',
            bottom: '15%',
            top: '20%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
            axisLine: { lineStyle: { color: '#4FC3F7' } },
            axisLabel: { 
                color: '#ffffff',
                interval: Math.max(1, Math.floor(xAxisData.length / 10))
            }
        },
        yAxis: {
            type: 'value',
            min: 90, // 调整最小值为90%，让变化更明显
            max: 100,
            axisLine: { lineStyle: { color: '#4FC3F7' } },
            axisLabel: { 
                color: '#ffffff',
                formatter: value => `${value}%`
            },
            splitLine: {
                lineStyle: { color: 'rgba(79, 195, 247, 0.2)' }
            }
        },
        series: series
    };

    chart.setOption(option, true);
}

/**
 * 失败响应码趋势图表（折线图）
 */
function createFailCodeTrendChart(elementId, data) {
    const chart = chartManager.getChart(elementId);
    if (!chart) return;

    const failCodes = data.failCodes || [];
    const timeData = data.timeData || [];
    const xAxisData = timeData.map(item => item.time);
    const series = [];

    // 取前5个失败响应码
    const topFailCodes = failCodes.slice(0, 5);
    
    topFailCodes.forEach((failCode, index) => {
        const trendData = timeData.map(timeItem => {
            // 模拟每个时间点的失败次数
            const baseCount = failCode.failCount / timeData.length;
            const randomFactor = 0.3 + Math.random() * 0.4; // 0.3-0.7的随机因子
            return Math.floor(baseCount * randomFactor);
        });
        
        series.push({
            name: `${failCode.retCode} - ${failCode.retDesc}`,
            type: 'line',
            data: trendData,
            smooth: true,
            lineStyle: {
                color: getRandomColor(index),
                width: 2
            },
            itemStyle: { color: getRandomColor(index) },
            symbol: 'circle',
            symbolSize: 4
        });
    });

    const option = {
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            },
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            borderColor: '#4FC3F7',
            textStyle: { color: '#ffffff' },
            formatter: function(params) {
                let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].name}</div>`;
                params.forEach(param => {
                    result += `
                        <div style="margin: 3px 0;">
                            ${param.marker} ${param.seriesName}: ${formatNumber(param.value)}
                        </div>
                    `;
                });
                return result;
            }
        },
        legend: {
            data: series.map(s => s.name),
            top: '5%',
            textStyle: { color: '#ffffff' },
            type: 'scroll',
            pageIconColor: '#4FC3F7',
            pageIconInactiveColor: '#666',
            pageTextStyle: { color: '#ffffff' }
        },
        grid: {
            left: '3%',
            right: '3%',
            bottom: '15%',
            top: '25%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
            axisLine: { lineStyle: { color: '#4FC3F7' } },
            axisLabel: { 
                color: '#ffffff',
                interval: Math.max(1, Math.floor(xAxisData.length / 8))
            }
        },
        yAxis: {
            type: 'value',
            axisLine: { lineStyle: { color: '#4FC3F7' } },
            axisLabel: { 
                color: '#ffffff',
                formatter: formatNumber
            },
            splitLine: {
                lineStyle: { color: 'rgba(79, 195, 247, 0.2)' }
            }
        },
        series: series,
        animationDuration: 1000,
        animationEasing: 'cubicOut'
    };

    chart.setOption(option, true);
}

/**
 * 中心交易量综合监控图表（包含交易量、成功笔数、失败笔数）
 */
function createCenterComprehensiveChart(elementId, centerData) {
    const chart = chartManager.getChart(elementId);
    if (!chart) return;

    const volumeData = centerData.volumeData || [];
    const xAxisData = volumeData.map(item => item.time);
    const totalData = volumeData.map(item => item.value);
    const successData = volumeData.map(item => Math.floor(item.value * (item.successRate || 98) / 100));
    const failData = volumeData.map((item, index) => totalData[index] - successData[index]);

    const option = {
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            },
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            borderColor: '#4FC3F7',
            textStyle: { color: '#ffffff' },
            formatter: function(params) {
                let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].name}</div>`;
                params.forEach(param => {
                    result += `
                        <div style="margin: 3px 0;">
                            ${param.marker} ${param.seriesName}: ${formatNumber(param.value)}
                        </div>
                    `;
                });
                return result;
            }
        },
        legend: {
            data: ['总交易量', '成功笔数', '失败笔数'],
            top: '5%',
            textStyle: { color: '#ffffff' }
        },
        grid: {
            left: '3%',
            right: '3%',
            bottom: '15%',
            top: '20%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
            axisLine: { lineStyle: { color: '#4FC3F7' } },
            axisLabel: { 
                color: '#ffffff',
                interval: Math.max(1, Math.floor(xAxisData.length / 8))
            }
        },
        yAxis: {
            type: 'value',
            name: '交易笔数',
            axisLine: { lineStyle: { color: '#4FC3F7' } },
            axisLabel: { 
                color: '#ffffff',
                formatter: formatNumber
            },
            splitLine: {
                lineStyle: { color: 'rgba(79, 195, 247, 0.2)' }
            }
        },
        series: [
            {
                name: '总交易量',
                type: 'line',
                data: totalData,
                smooth: true,
                lineStyle: { color: '#4FC3F7', width: 3 },
                itemStyle: { color: '#4FC3F7' },
                symbol: 'circle',
                symbolSize: 4
            },
            {
                name: '成功笔数',
                type: 'line',
                data: successData,
                smooth: true,
                lineStyle: { color: '#81C784', width: 2 },
                itemStyle: { color: '#81C784' },
                symbol: 'circle',
                symbolSize: 4
            },
            {
                name: '失败笔数',
                type: 'line',
                data: failData,
                smooth: true,
                lineStyle: { color: '#F44336', width: 2 },
                itemStyle: { color: '#F44336' },
                symbol: 'triangle',
                symbolSize: 4
            }
        ],
        animationDuration: 1000,
        animationEasing: 'cubicOut'
    };

    chart.setOption(option, true);
}

/**
 * 历史交易量趋势图表
 */
function createHistoryTrendChart(elementId, data, compareType = 'none') {
    const chart = chartManager.getChart(elementId);
    if (!chart) return;

    const currentData = data.current || [];
    const xAxisData = currentData.map(item => item.time);

    // 基础数据系列
    const series = [
        {
            name: '总交易量',
            type: 'bar',
            data: currentData.map(item => item.totalVolume),
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#4FC3F7' },
                    { offset: 1, color: 'rgba(79, 195, 247, 0.6)' }
                ])
            },
            emphasis: {
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#29B6F6' },
                        { offset: 1, color: 'rgba(41, 182, 246, 0.8)' }
                    ])
                }
            }
        },
        {
            name: '成功笔数',
            type: 'bar',
            data: currentData.map(item => item.successVolume),
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#81C784' },
                    { offset: 1, color: 'rgba(129, 199, 132, 0.6)' }
                ])
            }
        },
        {
            name: '失败笔数',
            type: 'bar',
            data: currentData.map(item => item.failVolume),
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#F44336' },
                    { offset: 1, color: 'rgba(244, 67, 54, 0.6)' }
                ])
            }
        }
    ];

    const option = {
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            },
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            borderColor: '#4FC3F7',
            textStyle: { color: '#ffffff' },
            formatter: function(params) {
                let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].name}</div>`;
                params.forEach(param => {
                    result += `
                        <div style="margin: 3px 0;">
                            ${param.marker} ${param.seriesName}: ${formatNumber(param.value)}
                        </div>
                    `;
                });
                return result;
            }
        },
        legend: {
            data: series.map(s => s.name),
            top: '5%',
            textStyle: { color: '#ffffff' },
            type: 'scroll',
            pageIconColor: '#4FC3F7',
            pageIconInactiveColor: '#666',
            pageTextStyle: { color: '#ffffff' }
        },
        grid: {
            left: '3%',
            right: '3%',
            bottom: '15%',
            top: '20%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
            axisLine: { lineStyle: { color: '#4FC3F7' } },
            axisLabel: { 
                color: '#ffffff',
                interval: Math.max(0, Math.floor(xAxisData.length / 12)),
                rotate: xAxisData.length > 20 ? 45 : 0
            }
        },
        yAxis: {
            type: 'value',
            name: '交易笔数',
            axisLine: { lineStyle: { color: '#4FC3F7' } },
            axisLabel: { 
                color: '#ffffff',
                formatter: formatNumber
            },
            splitLine: {
                lineStyle: { color: 'rgba(79, 195, 247, 0.2)' }
            }
        },
        series: series,
        animationDuration: 1500,
        animationEasing: 'cubicOut',
        dataZoom: xAxisData.length > 30 ? [
            {
                type: 'slider',
                start: Math.max(0, 100 - (30 / xAxisData.length * 100)),
                end: 100,
                height: 20,
                bottom: 0,
                textStyle: { color: '#ffffff' },
                fillerColor: 'rgba(79, 195, 247, 0.3)',
                borderColor: '#4FC3F7'
            },
            {
                type: 'inside',
                start: Math.max(0, 100 - (30 / xAxisData.length * 100)),
                end: 100
            }
        ] : undefined
    };

    chart.setOption(option, true);
}

// 页面卸载时清理图表
window.addEventListener('beforeunload', () => {
    chartManager.disposeAll();
});